<template>
  <div class="welfare-list pd-20">
    <el-button type="primary"
               @click="handleOption('add','null')">新 增</el-button>
    <el-table border
              :data="tableData"
              :span-method="handleSpan"
              style="width: 100%"
              class="mt-20">
      <el-table-column prop="goodsDeviceSaleSchemeId"
                       label="方案ID"
                       width="100"
                       align="center"></el-table-column>
      <el-table-column prop="schemaName"
                       label="方案名称"
                       width="200"
                       align="center"></el-table-column>
      <el-table-column prop="dataCount"
                       label="数据条数"
                       width="200"
                       align="center"></el-table-column>
      <el-table-column prop="awardType"
                       label="福利名称"
                       align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.awardType === 1">血糖试纸</span>
          <span v-if="scope.row.awardType === 2">血酮试纸</span>
          <span v-if="scope.row.awardType === 3">尿酸试纸</span>
          <span v-if="scope.row.awardType === 4">胆固醇试纸</span>
          <span v-if="scope.row.awardType === 5">报告解读</span>
        </template>
      </el-table-column>
      <el-table-column label="福利数量"
                       width="200"
                       prop="awardCount"
                       align="center">

      </el-table-column>
      <el-table-column prop="relateProducts"
                       label="关联产品"
                       align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.relateProducts === 1">个人版/个人包</span>
          <span v-if="scope.row.relateProducts === 2">全家版/全家包</span>
        </template>
      </el-table-column>
      <el-table-column prop="need"
                       label="关系"
                       align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.need === 1">必选</span>
          <span v-if="scope.row.need === 0">可选</span>
        </template>
      </el-table-column>
      <el-table-column prop="editField"
                       label="编辑"
                       width="100"
                       align="center">
        <template slot-scope="scope">
          <el-button type="primary"
                     @click="handleOption('edit',scope.row)">编 辑</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="delField"
                       label="删除"
                       width="100"
                       align="center">
        <template slot-scope="scope">
          <el-button type="danger"
                     @click="handleDel(scope.row)">删 除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!-- 新增 -->
    <el-dialog :title="title"
               :visible.sync="dialogVisible"
               width="50%"
               @close="dialogVisible = false">
      <el-form :model="formModel"
               :rules="formRules"
               ref="formRefs"
               label-width="80px">
        <el-form-item label="方案"
                      prop="scheme">
          <el-select v-model="formModel.schemeId"
                     placeholder="请选择方案"
                     clearable
                     @change="chagneScheme"
                     :disabled="currOption === 'edit'">
            <el-option v-for="item in schemeList"
                       :label="item.name"
                       :value="item.id"
                       :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <span>
        </span>
      </el-form>
      <el-table border
                :data="testData">
        <el-table-column prop="dataCount"
                         label="数据条数">
          <template slot-scope="scope">
            <el-input v-model="scope.row.dataCount"
                      :disabled="isRead"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="awardType"
                         label="赠送试纸">
          <template slot-scope="scope">
            <el-select v-model="scope.row.awardType"
                       placeholder="请选赠送试纸"
                       clearable>
              <el-option v-for="item in awardTypeList"
                         :label="item.label"
                         :value="item.id"
                         :key="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="awardCount"
                         label="数量">
          <template slot-scope="scope">
            <el-input v-model="scope.row.awardCount"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="need"
                         label="关系">
          <template slot-scope="scope">
            <el-select v-model="scope.row.need"
                       placeholder="请选赠送试纸"
                       clearable>
              <el-option v-for="item in needList"
                         :label="item.label"
                         :value="item.id"
                         :key="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="primary"
                       @click="handleAdd">新增</el-button>
            <el-button size="mini"
                       type="danger"
                       @click="handleDelRow(scope.$index, testData)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitForm(currOption)">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog :title="title"
               :visible.sync="dialogVisibleEdit"
               width="50%"
               @close="dialogVisibleEdit = false">
      <el-form :model="formModelEdit"
               :rules="formRulesEdit"
               ref="formRefsEdit"
               label-width="80px">
        <el-form-item label="方案"
                      prop="scheme">
          <el-select v-model="formModel.schemeId"
                     placeholder="请选择方案"
                     clearable
                     @change="chagneScheme"
                     :disabled="currOption === 'edit'">
            <el-option v-for="item in schemeList"
                       :label="item.name"
                       :value="item.id"
                       :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-table border
                :data="editTestData"
                :span-method="handleSpan">
        <el-table-column prop="dataCount"
                         label="数据条数">
          <template slot-scope="scope">
            <el-input v-model="scope.row.dataCount"
                      :disabled="isRead"
                      placeholder="请输入数据条数"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="awardType"
                         label="赠送试纸">
          <template slot-scope="scope">
            <el-select v-model="scope.row.awardType"
                       placeholder="请选赠送试纸"
                       clearable>
              <el-option v-for="item in awardTypeList"
                         :label="item.label"
                         :value="item.id"
                         :key="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="awardCount"
                         label="数量">
          <template slot-scope="scope">
            <el-input v-model="scope.row.awardCount"
                      placeholder="请输入数量"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="need"
                         label="关系">
          <template slot-scope="scope">
            <el-select v-model="scope.row.need"
                       placeholder="请选赠送试纸"
                       clearable>
              <el-option v-for="item in needList"
                         :label="item.label"
                         :value="item.id"
                         :key="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="primary"
                       @click="isEditHandleAdd()">新增</el-button>
            <el-button size="mini"
                       type="danger"
                       @click="isEditHandleDelRow(scope.$index, editTestData)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisibleEdit = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitForm(currOption)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {

    name: 'schemeList',
    data () {
      return {
        tableData: [],
        dialogVisible: false,
        dialogVisibleEdit: false,
        title: '',
        formModel: {
          scheme: '', // 方案名称
          schemeId: ''
        },
        formModelEdit: {
          scheme: '', // 方案名称
          schemeId: ''
        },
        schemeList: [
          { key: 1, label: '个人版/个人包' },
          { key: 2, label: '全家版/全家包' }
        ],

        formRules: {
          scheme: [
            { required: true, message: '请选择方案', trigger: 'change' }
          ]
        },
        formRulesEdit: {},
        currOption: '', // 提交类型,是新增还是编辑
        testData: [],
        editTestData: [],
        awardTypeList: [
          { id: 1, label: '血糖试纸' },
          { id: 2, label: '血酮试纸' },
          { id: 3, label: '尿酸试纸' },
          { id: 4, label: '总胆固醇试纸' },
          { id: 5, label: '报告解读' }
        ],
        needList: [
          { id: 1, label: '必选' },
          { id: 0, label: '可选' }
        ],
        isRead: true,
        queryDataCount: 0
      }
    },
    methods: {
      // colArr是要合并的层级。schemeId和schemeName是第一层，dataCount是第二层。newStr是数据列表。
      // 获取数据
      async getList () {
        const { data: res } = await this.post(this.api.schemeManager.queryWelfare)
        if (res.code === '200') {
          let colArr = [['goodsDeviceSaleSchemeId', 'schemaName', 'editField', 'delField'], ['']];
          let resData = res.object
          resData.forEach(item => {
            item.editField = '编辑'
            item.delField = '删除'
          })
          this.tableData = this.merge(colArr, resData);

        } else {
          this.$message.error(res.message)
        }
      },

      // 获取方案
      async getSchemeList () {
        const { data: res } = await this.post(this.api.schemeManager.querySchemes)
        if (res.code === '200') {
          this.schemeList = res.object
        } else {
          this.$message.error(res.message)
        }
      },
      // 操作
      handleOption (op, row) {
        switch (op) {
          case 'add':
            this.dialogVisible = true
            this.title = '新增福利配置'
            if (this.$refs['formRefs'] != undefined) {
              this.$refs['formRefs'].resetFields();
            }
            this.currOption = 'add'
            this.isRead = true
            this.getSchemeList()
            break
          case 'edit':
            this.dialogVisibleEdit = true
            this.title = '编辑福利配置'
            this.currOption = 'edit'
            this.getSchemeList()
            this.post(this.api.schemeManager.getWelfareById, {
              schemaId: row.goodsDeviceSaleSchemeId
            }).then(res => {
              if (res.data.code === '200') {
                let resData = res.data.object
                this.queryDataCount = resData[0].dataCount
                this.formModel.scheme = row.schemaName
                this.formModel.schemeId = row.goodsDeviceSaleSchemeId
                this.editTestData = resData;
              } else {
                this.$message.error(res.data.message)
              }
            })
            break
        }
      },
      // 选择方案
      async chagneScheme (val) {
        this.formModel.schemeId = val
        const { data: res } = await this.post(this.api.schemeManager.getSchemaId, {
          schemaId: val
        })
        if (res.code === '200') {
          let resData = res.object
          this.isRead = true
          this.queryDataCount = resData.dataCount
          this.testData.push({
            goodsDeviceSaleSchemeId: this.formModel.schemeId,
            dataCount: resData.dataCount,
            awardType: '', // 福利类型
            awardCount: '', // 福利数量
            need: '', // 1为true,0为false
            isRead: true
          })
        }
      },
      handleAdd () {
        let result = this.testData
        if (result.length > 0) {
          let item = result[result.length - 1]
          if (item.dataCount === '') {
            this.$message.error('请填写数据条数');
            return
          }
          if (item.awardType === '') {
            this.$message.error('请选择赠送试纸类型');
            return
          }
          if (item.awardCount === '') {
            this.$message.error('请填写赠送试纸数量');
            return
          }
          if (item.need === '') {
            this.$message.error('请选择关系');
            return
          }
          this.testData.push({
            goodsDeviceSaleSchemeId: this.formModel.schemeId,
            dataCount: this.queryDataCount,
            awardType: '', // 福利类型(1 血糖试纸,2 血酮试纸,3 尿酸试纸,4 胆固醇试纸,5 报告解读)
            awardCount: '', // 福利数量
            need: '', // 1为true,0为false
            isRead: true
          })
        } else {
          this.testData.push({
            goodsDeviceSaleSchemeId: this.formModel.schemeId,
            dataCount: this.queryDataCount,
            awardType: '', // 福利类型(1 血糖试纸,2 血酮试纸,3 尿酸试纸,4 胆固醇试纸,5 报告解读)
            awardCount: '', // 福利数量
            need: '', // 1为true,0为false
            isRead: true
          })
        }
      },
      isEditHandleAdd () {
        let res = this.editTestData
        if (res.length > 0) {
          let item = res[res.length - 1]
          if (item.dataCount === '') {
            this.$message.error('请填写数据条数');
            return
          }
          if (item.awardType === '') {
            this.$message.error('请选择赠送试纸类型');
            return
          }
          if (item.awardCount === '') {
            this.$message.error('请填写赠送试纸数量');
            return
          }
          if (item.need === '') {
            this.$message.error('请选择关系');
            return
          }

          this.editTestData.push({
            goodsDeviceSaleSchemeId: this.formModel.schemeId,
            dataCount: this.queryDataCount,
            awardType: '', // 福利类型
            awardCount: '', // 福利数量
            need: '', // 1为true,0为false
            isRead: false
          })

        } else {
          this.editTestData.push({
            goodsDeviceSaleSchemeId: this.formModel.schemeId,
            dataCount: this.queryDataCount,
            awardType: '', // 福利类型
            awardCount: '', // 福利数量
            need: '', // 1为true,0为false
            isRead: false
          })
        }

      },
      handleDelRow (index, row) {
        if (row.length == 1) {
          this.$message.warning('至少保留一个福利')
        } else {
          row.splice(index, 1);
        }
      },
      isEditHandleDelRow (index, row) {
        if (row.length == 1) {
          this.$message.warning('至少保留一个福利')
        } else {
          row.splice(index, 1);
        }
      },
      // 提交
      async submitForm (op) {
        switch (op) {
          case 'add':
            let result = this.testData
            if (result.length > 0) {
              let item = result[result.length - 1]
              if (item.dataCount === '') {
                this.$message.error('请填写数据条数');
                return
              }
              if (item.awardType === '') {
                this.$message.error('请选择赠送试纸类型');
                return
              }
              if (item.awardCount === '') {
                this.$message.error('请填写赠送试纸数量');
                return
              }
              if (item.need === '') {
                this.$message.error('请选择关系');
                return
              }
              const { data: res } = await this.post(this.api.schemeManager.addWelfare, {
                goodsDeviceSaleAwardDtos: this.testData
              })
              if (res.code === '200') {
                this.$message.success('新增成功')
                this.getList()
                this.dialogVisible = false
              } else {
                this.$message.error(res.message)
              }
            }
            break
          case 'edit':
            let resData = this.editTestData
            if (resData.length > 0) {
              let item = resData[resData.length - 1]
              if (item.dataCount === '') {
                this.$message.error('请填写数据条数');
                return
              }
              if (item.awardType === '') {
                this.$message.error('请选择赠送试纸类型');
                return
              }
              if (item.awardCount === '') {
                this.$message.error('请填写赠送试纸数量');
                return
              }
              if (item.need === '') {
                this.$message.error('请选择关系');
                return
              }
              const { data: retult } = await this.post(this.api.schemeManager.modifyWelfare, {
                goodsDeviceSaleAwardDtos: this.editTestData
              })
              if (retult.code === '200') {
                this.$message.success('保存成功')
                this.getList();
                this.dialogVisibleEdit = false;
              } else {
                this.$message.error(retult.message);
              }
            } else {
              this.$message.error('至少保留一个福利');
            }

            break
        }
      },

      // 合并行计算
      merge (colArr, list) {
        let allProps = [];
        colArr.forEach((props, index) => {
          allProps.push(...props);
          list = this.getLevel(props, allProps, list);
        });
        return list;
      },
      // 组装层
      getLevel (props, allProps, list) {
        var rowKey = {};
        for (var item of list) {
          let propInfo = this.getPropStr(allProps, item);
          if (rowKey[propInfo.key]) {
            rowKey[propInfo.key].children.push(item);
          } else {
            let obj = propInfo;
            obj.children = [item];
            rowKey[propInfo.key] = obj;
          }
        }
        let info = [];
        for (var key in rowKey) {
          rowKey[key].children.forEach((item, index) => {
            if (index == 0) {
              item = Object.assign(
                item,
                this.getMergeInfo(props, rowKey[key].children.length)
              );
            } else {
              item = Object.assign(item, this.getMergeInfo(props, 0));
            }
            info.push(item);
          });
        }
        return info;
      },
      // 获取合并信息
      getMergeInfo (props, num) {
        let obj = {};
        props.forEach(item => {
          obj[item + "_merge"] = {
            rowspan: num,
            colspan: 1
          };
        });
        return obj;
      },
      // 把属性的值拼接在一起,并和属性的值一起返回。
      getPropStr (props, info) {
        let obj = {};
        let propStr = props.map(item => {
          obj[item] = info[item];
          return info[item];
        });
        obj.key = propStr.toString();
        return obj;
      },
      // 表格合并
      handleSpan ({ row, column, rowIndex, columnIndex }) {
        if (row[column.property + "_merge"]) {
          return row[column.property + "_merge"];
        } else {
          return { rowspan: 1, colspan: 1 };
        }
      },
      // 删除
      handleDel (row) {
        this.$confirm('确认删除？')
          .then(_ => {
            this.post(this.api.schemeManager.delWelfare, {
              schemeId: row.goodsDeviceSaleSchemeId
            }).then(res => {
              if (res.data.code === '200') {
                this.$message.success('删除成功')
                this.getList()
              } else {
                this.$message.error(res.data.message)
              }
            })
          })
          .catch(_ => { });
      }
    },
    created () {
      this.getList()
    }
  }
</script>
<style scoped lang="scss">
  .table-cell {
    border-bottom: 1px solid #dcdfe6;
    border-right: 1px solid #dcdfe6;
    td,
    th {
      height: 46px;
      line-height: 46px;
      border: 1px solid #dcdfe6;
      text-align: center;
    }
    th {
      border-bottom: none;
      border-right: none;
    }
    td {
      border-right: none;
      border-bottom: none;
    }
  }
</style>